package com.hefan.api.controller.pay;

import java.math.BigDecimal;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import com.alibaba.fastjson.JSON;
import com.cat.common.meta.PaymentTypeEnum;
import com.cat.common.meta.TradeLogPayStatusEnum;
import com.cat.tiger.util.CollectionUtils;
import com.hefan.api.service.pay.PayNotifyOprateLocalService;
import com.hefan.common.pay.alipay.Base64;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.cat.common.entity.ResultBean;
import com.cat.common.meta.ResultCode;
import com.hefan.api.service.pay.PayLocalService;
import com.hefan.common.util.HttpUtils;
import com.hefan.pay.bean.PayExtendVo;
import com.hefan.pay.bean.TradeLog;
import com.hefan.user.bean.WebUser;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/v1/pay")
public class PayOrderForAppController {

	private Logger logger = LoggerFactory.getLogger(PayOrderForAppController.class);
	@Resource
	private PayLocalService payLocalService;

	@Resource
	private PayNotifyOprateLocalService payNotifyOprateLocalService;

	@RequestMapping("/appPayOrder")
	@ResponseBody
	public String appPayOrder(HttpServletRequest req) {
		ResultBean result = new ResultBean(ResultCode.SUCCESS, null);
		try {
			Map map = HttpUtils.initParam(req, Map.class);
			if (CollectionUtils.isEmpty(map) || !map.containsKey("userId") || !map.containsKey("paymentType")
					|| !map.containsKey("id")) {
				return JSON.toJSONString(new ResultBean(ResultCode.ParamException, null));
			}
			String userId = String.valueOf(map.get("userId"));
			int paymentType = Integer.valueOf(String.valueOf(map.get("paymentType")));
			PaymentTypeEnum paymentTypeEnum = PaymentTypeEnum.getPaymentTypeEnumByPaymentType(paymentType);
			if (StringUtils.isBlank(userId) || paymentTypeEnum == null) {
				return JSON.toJSONString(new ResultBean(ResultCode.ParamException, null));
			}
			int exchangeRechargeId = Integer.valueOf(String.valueOf(map.get("id")));
			// 如果是ios支付 exchangeRechargeId 不能为 0
			if (exchangeRechargeId == 0
					&& paymentTypeEnum.getPaymentType() == paymentTypeEnum.IOS_APPLE_PAY.getPaymentType()) {
				return JSON.toJSONString(new ResultBean(ResultCode.ParamException, null));
			}
			String fanpiao = "0";
			if (Integer.valueOf(String.valueOf(map.get("id"))) == 0) {
				if (!map.containsKey("fanpiao") || StringUtils.isBlank(String.valueOf(map.get("fanpiao")))) {
					return JSON.toJSONString(new ResultBean(ResultCode.ParamException, null));
				}
				fanpiao = String.valueOf(map.get("fanpiao"));
			}
			TradeLog tradeLog = new TradeLog();
			tradeLog.setUserId(userId);
			tradeLog.setPaymentType(paymentType);
			tradeLog.setIncome(Integer.valueOf(fanpiao));
			PayExtendVo payExtendVo = new PayExtendVo();
			payExtendVo.setUserId(userId);
			result = payLocalService.createOrder(paymentTypeEnum, tradeLog, payExtendVo, exchangeRechargeId, req);
		} catch (Exception e) {
			e.printStackTrace();
			return JSON.toJSONString(new ResultBean(ResultCode.UnknownException, null));
		}

		return JSON.toJSONString(result);
	}

	/**
	 * 苹果内购支付检查
	 * 
	 * @param req
	 * @return
	 */
	@RequestMapping("/appStorePayCheck")
	@ResponseBody
	public String AppleAppStorePayCheck(HttpServletRequest req) {
		ResultBean result = new ResultBean(ResultCode.SUCCESS, null);
		try {
			Map params = HttpUtils.initParam(req, Map.class);
			if (CollectionUtils.isEmpty(params) || !params.containsKey("orderId")
					|| !params.containsKey("appleReceipt")) {
				return JSON.toJSONString(new ResultBean(ResultCode.ParamException, null));
			}
			String orderId = String.valueOf(params.get("orderId"));
			String appleReceipt = String.valueOf(params.get("appleReceipt"));
			String transactionId = "";
			if(params.containsKey("transactionId") ) {
				transactionId =  String.valueOf(params.get("transactionId"));
			}
			//logger.info("AppleAppStorePayCheck ----- appleReceipt:"+appleReceipt);
			//logger.info("AppleAppStorePayCheck -----pass appleReceipt:"+ new String(Base64.decode(appleReceipt)));
			if (StringUtils.isBlank(orderId) || StringUtils.isBlank("appleReceipt")) {
				return JSON.toJSONString(new ResultBean(ResultCode.ParamException, null));
			}
			// 苹果内购 支付检查
			result = payNotifyOprateLocalService.appleAppStoreCheckOprate(orderId, appleReceipt,transactionId);
		} catch (Exception e) {
			logger.error(e.getMessage());
			return JSON.toJSONString(new ResultBean(ResultCode.UnknownException, null));
		}
		return JSON.toJSONString(result);
	}

	/**
	 * 根据ID查询订单状态
	 * 
	 * @param req
	 * @return
	 */
	@RequestMapping("/getTradeLogByOrderId")
	@ResponseBody
	public String getTradeLogByOrderId(HttpServletRequest req) {
		ResultBean resultBean = new ResultBean();
		try{
			Map map = HttpUtils.initParam(req, Map.class);
			String orderId = String.valueOf(map.get("orderId"));
			resultBean.setCode(ResultCode.SUCCESS.get_code());
			resultBean.setData(payLocalService.getTradeLogByOrderId(orderId));
		}catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			resultBean.setData(ResultCode.UnknownException);
			resultBean.setData(e.getMessage());
		}
		return JSON.toJSONString(resultBean);	
	}

}
